import sys
from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                               QPushButton, QLabel, QStackedWidget, QFileDialog,
                               QProgressBar, QMessageBox, QTabWidget)
from PySide6.QtGui import QIcon, QFont, QPalette, QColor
from PySide6.QtCore import Qt, QSize, QTimer

from database.db_manager import DBManager
from ui.word_card import WordCardWidget
from ui.word_list import WordListWidget
from ui.stats_widget import StatsWidget
from utils.json_importer import JSONImporter

class MainWindow(QMainWindow):
    """应用主窗口"""
    
    def __init__(self):
        super().__init__()
        self.db_manager = DBManager()
        self.json_importer = JSONImporter(self.db_manager)
        
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        # 设置窗口属性
        self.setWindowTitle("Vocabulary Master")
        self.setMinimumSize(800, 600)
        
        # 创建中心部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # 创建顶部导航栏
        nav_layout = QHBoxLayout()
        nav_layout.setContentsMargins(10, 10, 10, 5)
        
        # 导航按钮
        self.btn_learn = QPushButton("学习")
        self.btn_learn.setCheckable(True)
        self.btn_learn.setChecked(True)
        self.btn_learn.clicked.connect(lambda: self.switch_view(0))
        
        self.btn_list = QPushButton("单词表")
        self.btn_list.setCheckable(True)
        self.btn_list.clicked.connect(lambda: self.switch_view(1))
        
        self.btn_stats = QPushButton("学习统计")
        self.btn_stats.setCheckable(True)
        self.btn_stats.clicked.connect(lambda: self.switch_view(2))
        
        self.btn_import = QPushButton("导入词库")
        self.btn_import.clicked.connect(self.import_words)
        
        # 添加按钮到导航栏
        for btn in [self.btn_learn, self.btn_list, self.btn_stats, self.btn_import]:
            btn.setMinimumHeight(35)
            nav_layout.addWidget(btn)
        
        nav_layout.addStretch()
        main_layout.addLayout(nav_layout)
        
        # 创建堆叠窗口用于切换不同视图
        self.stacked_widget = QStackedWidget()
        
        # 创建各个视图
        self.learn_view = WordCardWidget(self.db_manager)
        self.list_view = WordListWidget(self.db_manager)
        self.stats_view = StatsWidget(self.db_manager)
        
        # 添加视图到堆叠窗口
        self.stacked_widget.addWidget(self.learn_view)
        self.stacked_widget.addWidget(self.list_view)
        self.stacked_widget.addWidget(self.stats_view)
        
        main_layout.addWidget(self.stacked_widget)
        
        # 创建状态栏
        self.status_bar = self.statusBar()
        self.status_bar.showMessage("就绪")
        
        # 应用样式
        self.apply_styles()
        
    def apply_styles(self):
        """应用样式表"""
        self.setStyleSheet('''
            QMainWindow, QWidget {
                background-color: #f5f5f7;
            }
            
            QPushButton {
                background-color: #0071e3;
                color: white;
                border-radius: 8px;
                padding: 8px 16px;
                font-size: 14px;
                border: none;
            }
            
            QPushButton:hover {
                background-color: #0077ed;
            }
            
            QPushButton:pressed {
                background-color: #0066cc;
            }
            
            QPushButton:checked {
                background-color: #005cc5;
            }
            
            QPushButton#btn_import {
                background-color: #34c759;
            }
            
            QPushButton#btn_import:hover {
                background-color: #32ad53;
            }
            
            QLabel {
                font-size: 14px;
                color: #1c1c1e;
            }
            
            QStackedWidget {
                background-color: transparent;
            }
        ''')
        
    def switch_view(self, index):
        """切换视图"""
        self.stacked_widget.setCurrentIndex(index)
        
        # 更新按钮状态
        buttons = [self.btn_learn, self.btn_list, self.btn_stats]
        for i, btn in enumerate(buttons):
            btn.setChecked(i == index)
            
        # 更新状态栏消息
        views = ["学习模式", "单词列表", "学习统计"]
        self.status_bar.showMessage(views[index])
        
        # 刷新当前视图数据
        current_widget = self.stacked_widget.currentWidget()
        if hasattr(current_widget, 'refresh_data'):
            current_widget.refresh_data()
        
    def import_words(self):
        """导入单词JSON文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择JSON词库文件", "", "JSON Files (*.json)"
        )
        
        if not file_path:
            return
            
        self.status_bar.showMessage("正在导入词库...")
        count, message = self.json_importer.import_from_file(file_path)
        
        # 显示导入结果
        QMessageBox.information(self, "导入结果", message)
        self.status_bar.showMessage(f"就绪 - {message}")
        
        # 刷新单词列表
        if hasattr(self.list_view, 'refresh_data'):
            self.list_view.refresh_data()